﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZG_member.BLL;
using System.Configuration;


namespace ZG_member
{
    public partial class RechargeForm : Form
    {
        public VisualCardPrinter_NPPrinter_New.VisualCardPrinter_NPPrinter vnp;
        int ret;
        MainForm mainfrom;
        string id = "0";
        string memberIds = "0";
        public RechargeForm(MainForm main, string id1,string memberId, VisualCardPrinter_NPPrinter_New.VisualCardPrinter_NPPrinter VNp)
        {
            InitializeComponent();
            mainfrom = main;
            vnp = VNp;
            id = id1;
            memberIds = memberId;
            skinEngine1.SkinFile = Application.StartupPath + ConfigurationManager.AppSettings["Skin"];
        }

        memberInfo meberfo = new memberInfo();

        Model.memberInfo memberInfoMod = new Model.memberInfo();
        private void RechargeForm_Load(object sender, EventArgs e)
        {
            this.Opacity = 0;
            this.timer1.Start();

            string mima;
            string status;
            try
            {
                //mima = vnp.ZSGW_KeyPass(vnp.RfidCardRequestAndReadNum());

                //status = vnp.RfidCardRequestAndReadData("1", mima);
                status = vnp.RfidCardRequestAndReadData("1", "FFFFFFFFFFFF");
            }
            catch (Exception)
            {

                MessageBox.Show("此卡不是本公司的卡片！请与本公司联系。电话：010-51291008");
                return;
            }


            if (status == "1")
            {
                //MessageBox.Show("机器未插卡");
            }
            else
                if (status == "0")
                {
                    //MessageBox.Show("端口未打卡");
                }
                else
                {
                    //string data = "";
                    //byte blocknum = 1;
                    //VN.WriteData(blocknum, data);
                    //return;
                    //VN.ReadData(blocknum, ref data);
                    //this.TxtCardId.Text = status;
                    id = status;
                }

            memberInfo member = new memberInfo();
            Model.memberInfo memberMod = new Model.memberInfo();
            try
            {
                //if (status != 0x02)
                //{

                memberMod = member.GetModeCard(id);
                if (memberMod == null)
                {
                    memberMod = member.GetModels(memberIds);
                }
                //}
                //else
                //{
                //    memberMod = member.GetModelList("memberCardId='" + this.TxtConsumerId.Text + "'")[0];
                //}

            }
            catch
            {

                MessageBox.Show("找不到该会员");
                return;
            }

            MemberSaleForm m = new MemberSaleForm(mainfrom,id, this.TxtConsumerId.Text, vnp);
            if (!m.test(memberMod))
            {
                this.Close();
                return;
            }

            this.TxtConsumerId.Text = memberMod.memberId;
            this.TxtBalance.Text = memberMod.Balance.ToString();
            this.TxtName.Text = memberMod.memberName;
            this.TxtIntegral.Text = memberMod.point.ToString();



            TxtRechageMoney.ReadOnly = true;
            TxtName.ReadOnly = true;
            TxtIntegral.ReadOnly = true;
            //TxtConsumerId.ReadOnly = true;
            TxtBalance.ReadOnly = true;


        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReadCards_Click(object sender, EventArgs e)
        {
            TxtDelete();
            memberInfo meberfo = new memberInfo();

            Model.memberInfo meberInfoMod = new Model.memberInfo();
            try
            {
                meberInfoMod = meberfo.GetModelList("memberId='" + TxtConsumerId.Text + "'")[0];
            }
            catch
            {

                MessageBox.Show("找不到该会员");
                return;
            }
            TxtName.Text = meberInfoMod.memberName;
            TxtBalance.Text = meberInfoMod.Balance.Value.ToString("#0.0");
            TxtIntegral.Text = meberInfoMod.point.ToString();
            TxtRechageMoney.Text = meberInfoMod.Balance.Value.ToString("#0.0");
        }

        /// <summary>
        /// 会员充值金额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtRechargeAmount_TextChanged(object sender, EventArgs e)
        {
            try
            {
                this.TxtRechageMoney.Text = this.TxtBalance.Text;
                if (this.TxtRechargeAmount.Text == "")
                {

                }
                else
                {
                    this.TxtSendMoney.Text = Savpart(decimal.Parse(decimal.Parse(TxtRechargeAmount.Text).ToString("F1")));
                }
                if (TxtRechageMoney.Text == "") { }
                else
                {
                    if (this.TxtRechargeAmount.Text == "")
                    {
                        TxtRechageMoney.Text = (decimal.Parse(this.TxtSendMoney.Text) + decimal.Parse(this.TxtBalance.Text)).ToString("#0.0");
                    }
                    else
                    {
                        TxtRechageMoney.Text = (decimal.Parse(this.TxtRechargeAmount.Text) + decimal.Parse(this.TxtSendMoney.Text) + decimal.Parse(this.TxtBalance.Text)).ToString("#0.0");
                    }


                }
            }
            catch (Exception)
            {

                return;
            }
          
        }
        public string Savpart(decimal price)
        {
            Model.consumeSolution cm = new Model.consumeSolution();
            consumeSolution cs = new consumeSolution();
            memberInfo m = new memberInfo();
            Model.memberInfo mi = m.GetUserIdMode(id);
            if (id == "0")
            {
                mi = m.GetModels(memberIds);
            }

            cm = cs.GetModel((int)mi.cardType);
            string savingSolution = cm.savingSolution;
            string[] one = savingSolution.Split('|');
            string part = "0";
            for (int i = 0; i < one.Length; i++)
            {
                string[] two = one[i].Split(',');

                if (two[0] == "")
                {
                    return part;
                }
                else
                {
                    if (price >= int.Parse(two[0]))
                    {
                        decimal beishu = price / int.Parse(two[0]);
                        part = (beishu * int.Parse(two[1])).ToString("F1");
                    }
                }
            }
            return part;
        }
        /// <summary>
        /// 结算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRecharge_Click(object sender, EventArgs e)
        {



            memberInfo meberfo = new memberInfo();

            Model.memberInfo memberInfoMod = new Model.memberInfo();
            try
            {
                memberInfoMod = meberfo.GetModels(TxtConsumerId.Text);
            }
            catch
            {
                MessageBox.Show("请选择会员");
                return;
            }
            if (memberInfoMod.status == 2)
            {
                MessageBox.Show("您的卡片已停用！");
                return;
            }
            memberInfoMod.Balance = decimal.Parse(TxtRechageMoney.Text);
            meberfo.Update(memberInfoMod);
            //memberInfoMod.point = int.Parse(TxtRechageMoney.Text);
            wasteBook wastebook = new wasteBook();
            Model.wasteBook wasteBookMod = new Model.wasteBook();

            wasteBookMod.memberCardId = this.TxtConsumerId.Text;
            wasteBookMod.consumeTimes = wasteBookMod.consumeTimes + 1;
            wasteBookMod.operatorId = MainForm.Operator;
            wasteBookMod.consumeType = memberInfoMod.cardType;
            wasteBookMod.cardPayMoney = 0;
            wasteBookMod.cashPayMoney = 0;
            wasteBookMod.consumeMoney = 0;
            wasteBookMod.consumeIntegral = 0;
            wasteBookMod.totalIntegral = 0;
            wasteBookMod.exchangeIntegral = 0;
            wasteBookMod.savingMoney = decimal.Parse(TxtRechargeAmount.Text);
            wasteBookMod.refundmentIntegral = 0;
            wasteBookMod.refundmentMoney = 0;
            wasteBookMod.cardBalance = decimal.Parse(TxtRechageMoney.Text);
            wasteBookMod.date = DateTime.Parse(DateTime.Now.ToString());
            wasteBookMod.details = ConfigurationManager.AppSettings["details"];
            wastebook.Add(wasteBookMod);

            #region 将充值金额添加到销售人下
            ZG_member.BLL.SalesStaffList sale = new ZG_member.BLL.SalesStaffList();
            ZG_member.Model.SalesStaffList saleMode = new ZG_member.Model.SalesStaffList();
            string saleID = memberInfoMod.OpenTeacher;
            saleMode = sale.GetModel(saleID);
            saleMode.Money = saleMode.Money + Convert.ToDouble(this.TxtRechargeAmount.Text);
            sale.Update(saleMode);
            ZG_member.BLL.SalesWasteBook saleWaste = new ZG_member.BLL.SalesWasteBook();
            ZG_member.Model.SalesWasteBook saleWasteMode = new ZG_member.Model.SalesWasteBook();
            saleWasteMode.SalesPersonId = saleMode.SalesPersonId;
            saleWasteMode.Dates = DateTime.Now;
            saleWasteMode.Source = "充值";
            saleWasteMode.money = Convert.ToDouble(this.TxtRechargeAmount.Text);
            saleWasteMode.memberId = memberInfoMod.memberId;
            saleWaste.add(saleWasteMode);
            #endregion

            if (CbxPrint.Checked)
            {
                printPreviewDialog1.Document = this.printDocument1;
                this.printDocument1.PrintController = new System.Drawing.Printing.StandardPrintController();
                printPreviewDialog1.Document.Print();
                DialogResult dt = MessageBox.Show("是否继续打印？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dt == DialogResult.Yes)
                {
                    printPreviewDialog1.Document = this.printDocument1;
                    this.printDocument1.PrintController = new System.Drawing.Printing.StandardPrintController();
                    printPreviewDialog1.Document.Print();
                }

            }
            string mima;
            string status;
            try
            {
                mima = vnp.ZSGW_KeyPass(vnp.RfidCardRequestAndReadNum());

                //status = vnp.RfidCardRequestAndReadData("1", mima);
                status = vnp.RfidCardRequestAndReadData("1", mima);
            }
            catch (Exception)
            {

                throw;
            }
            if (status == "0" || status == "1")
            {

            }
            else
            {

                MemberSaleForm mb = new MemberSaleForm(mainfrom,id, this.TxtConsumerId.Text, vnp);
                Model.memberInfo mode = mb.GetModel();
                int Nowday = DateTime.Now.Day;
                int Nowyue = DateTime.Now.Month;

                int shengriday = ((DateTime)mode.birthDay).Day;
                int shengriyue = ((DateTime)mode.birthDay).Month;
                IntegrationExchangeForm i = new IntegrationExchangeForm(mainfrom, this.TxtConsumerId.Text, vnp);
                //i.keyongjifen(mode.memberId, (int)mode.cardType);
                //int keyong = (int)mode.point - int.Parse(i.keyongjifen(mode.memberId, (int)mode.cardType));
                int jifen = 0;
                try
                {
                    jifen = (int)mode.point - int.Parse(i.keyongjifen(mode.memberId.ToString(), (int)mode.cardType));
                }
                catch (Exception)
                {
                    jifen = 0;
                }
                consumeSolution ct = new consumeSolution();
                Model.consumeSolution cs = ct.GetModel((int)mode.cardType);
                string sex = (bool)mode.sex ? "男" : "女";
                                                         //"会员卡号#卡片类型#会员姓名#性　　别         #卡片状态                  #办卡日期                    #截止日期                 #累计积分#本次积分#可用积分#本次消费              #储值余额#折扣金额#本次充值                  #积分支付#现金消费#空　　行";
                string[] ModelArray = new string[] { mode.memberId, cs.solutionName, mode.memberName, sex, "正常",Convert.ToDateTime(mode.createDate).ToString("yyyy-MM-dd"),Convert.ToDateTime(mode.expiresDate).ToString("yyyy-MM-dd"), mode.point.ToString(), "0", jifen.ToString(), "0", this.TxtRechageMoney.Text, "0", this.TxtRechargeAmount.Text, "0", "0", "" };
                string Go = mb.print(ModelArray);
                Go = "\n" + Go;
                birthdayremind br = new birthdayremind();
                Model.birthdayremind brmodl = br.GetModel(2);
                int aa = br.tixingday(this.TxtConsumerId.Text);
                if (aa < brmodl.Remindday && aa != 0)
                {
                    if (Nowyue == shengriyue)
                    {
                        if (Nowday < shengriday)
                        {
                            string one = brmodl.Remindcontent.Replace("{now}", DateTime.Now.ToString("yyyy-MM-dd") + "\n");
                            string two = one.Replace("{leftDays}", aa.ToString());
                            Go += two + "\n";
                        }
                    }
                    if (Nowyue < shengriyue)
                    {
                        string one = brmodl.Remindcontent.Replace("{now}", DateTime.Now.ToString("yyyy-MM-dd") + "\n");
                        string two = one.Replace("{leftDays}", aa.ToString());
                        Go += two + "\n";
                    }
                }
                else if (aa == 0)
                {
                    Go +=mb.AdvPreProcess(brmodl.Nowremindcontent1) + "\n";
                }
                vnp.PrintBufferClear();
                vnp.PrintCharacterDataSetting(Go);
                vnp.ErasePrintDischarge3();
                mainfrom.shifouxianshi(MainForm.Operator);

            }
            MessageBox.Show("充值成功");
            mainfrom.shifouxianshi(MainForm.Operator);
            this.Close();


        }
        public ZG_member.Model.memberInfo GetModel()
        {
            memberInfo m = new memberInfo();
            ZG_member.Model.memberInfo mem = m.GetModelFormemberCardId(id);
            return mem;
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            consumeSolution ct = new consumeSolution();

            Model.memberInfo mode = GetModel();
            Model.consumeSolution css = ct.GetModel(Convert.ToInt32(mode.cardType));
            //string xiaopiaoprint = gettemplates(1);
            string xiaopiaoprint = "";
            IntegrationExchangeForm integ = new IntegrationExchangeForm(mainfrom, this.TxtConsumerId.Text, vnp);
            BLL.wasteBook bk = new BLL.wasteBook();
            integ.keyongjifen(mode.memberId, (int)mode.cardType);


            int point = Convert.ToInt32(this.TxtIntegral.Text);
            int keyong = (int)mode.point - int.Parse(integ.keyongjifen(mode.memberId, (int)mode.cardType));
            string sex = (bool)mode.sex ? "男" : "女";
            string wastebk = "";

            wastebk = bk.GetMaxId().ToString();



            string insertString = "";


            goods good = new goods();
            ZG_member.Model.goods goodsMode = new ZG_member.Model.goods();
            //xiaopiaoprint = print(ModelArray);
            //int sa = xiaopiaoprint.IndexOf("附加信息");
            insertString += "          心悦会所\n";
            insertString += "----------------------------\n";
            insertString += css.solutionName + "\n";
            insertString += "流水号:" + wastebk + "\n";
            insertString += "现有积分:" + mode.point + "\n";
            insertString += "卡内余额:" + this.TxtBalance.Text + "\n";
            insertString += "充值金额:" + Convert.ToDecimal(this.TxtRechargeAmount.Text) + Convert.ToDecimal(this.TxtSendMoney.Text) + "\n";
            insertString += "充后金额:" + mode.Balance + "\n";
            insertString += "附加信息:\n";
            insertString += "时间:" + DateTime.Now.ToLocalTime() + "\n";
            xiaopiaoprint += insertString;
            xiaopiaoprint += "\n\n操作员：" + MainForm.Operator + "\n";
            xiaopiaoprint += "客户签名：\n  \n  \n  \n \n------------------------------------";
            e.Graphics.DrawString(xiaopiaoprint, new Font("黑体", 9, FontStyle.Regular), Brushes.Black, 10, 10);

        }
        /// <summary>
        /// 修改赠送金额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtSendMoney_TextChanged(object sender, EventArgs e)
        {
            if (TxtRechageMoney.Text == "") { }
            else
            {
                if (TxtSendMoney.Text == "" && TxtRechargeAmount.Text != "")
                {
                    TxtRechageMoney.Text = (decimal.Parse(TxtRechageMoney.Text) + decimal.Parse(TxtRechargeAmount.Text)).ToString("#0.0");
                }
                else if (TxtRechargeAmount.Text == "" && TxtSendMoney.Text != "")
                {
                    TxtRechageMoney.Text = (decimal.Parse(TxtRechageMoney.Text) + decimal.Parse(TxtSendMoney.Text)).ToString("#0.0");
                }
                else if (TxtRechargeAmount.Text == "" && TxtSendMoney.Text == "")
                {

                }
                else
                {
                    TxtRechageMoney.Text = (decimal.Parse(TxtRechageMoney.Text) + decimal.Parse(TxtRechargeAmount.Text) + decimal.Parse(TxtSendMoney.Text)).ToString("#0.0");
                }
            }
        }
        /// <summary>
        /// 删除文本框数值
        /// </summary>
        private void TxtDelete()
        {
            TxtRechageMoney.Text = "";
            TxtRechargeAmount.Text = "";
            TxtSendMoney.Text = "";
            TxtName.Text = "";
            TxtIntegral.Text = "";
            TxtBalance.Text = "";
        }

        private void TxtRechargeAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            
        }

        private void TxtSendMoney_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //timer开启
            this.Left += 2;
            this.Opacity += 0.1;
            if (Opacity == 1)
            {
                this.timer1.Stop();

            }
        }



        int flag = 0;
        private void RechargeForm_FormClosing_1(object sender, FormClosingEventArgs e)
        {
            if (flag == 0)
            {
                e.Cancel = true;
                flag = 1;
                this.timer2.Start();
            }
        }

        private void timer2_Tick_1(object sender, EventArgs e)
        {
            //timer关闭
            this.Top = this.Top + 10;
            this.Opacity = this.Opacity - 0.06;
            if (Opacity <= 0)
            {
                this.timer2.Stop();
                this.Close();
            }
        }

        private void TxtConsumerId_Leave(object sender, EventArgs e)
        {
            if (this.TxtName.Text == "")
            {
                string mima;
                string status;
                try
                {
                    //mima = vnp.ZSGW_KeyPass(vnp.RfidCardRequestAndReadNum());

                    status = vnp.RfidCardRequestAndReadData("1", "FFFFFFFFFFFF");
                }
                catch (Exception)
                {

                    throw;
                }
                if (status == "1")
                {
                    //MessageBox.Show("机器未插卡");
                }
                else
                    if (status == "0")
                    {
                        MessageBox.Show("端口未打卡");
                    }
                    else
                    {
                        //string data = "";
                        //byte blocknum = 1;
                        //VN.WriteData(blocknum, data);
                        //return;
                        //VN.ReadData(blocknum, ref data);
                        this.TxtConsumerId.Text = status;
                        //id = this.TxtCardId.Text;
                    }

                memberInfo member = new memberInfo();
                Model.memberInfo memberMod = new Model.memberInfo();
                try
                {
                    if (status == "1" || status == "0")
                    {
                        memberMod = member.GetModelList("memberId='" + this.TxtConsumerId.Text + "'")[0];
                    }
                    else
                    {
                        memberMod = member.GetModelList("memberCardId='" + this.TxtConsumerId.Text + "'")[0];
                    }

                }
                catch
                {

                    MessageBox.Show("找不到该会员");
                    return;
                }

                MemberSaleForm m = new MemberSaleForm(mainfrom,memberMod.memberCardId, this.TxtConsumerId.Text, vnp);
                m.test(memberMod);

                this.TxtConsumerId.Text = memberMod.memberId;
                this.TxtBalance.Text = memberMod.Balance.ToString();
                this.TxtName.Text = memberMod.memberName;
                this.TxtIntegral.Text = memberMod.point.ToString();



                TxtRechageMoney.ReadOnly = true;
                TxtName.ReadOnly = true;
                TxtIntegral.ReadOnly = true;
                //TxtConsumerId.ReadOnly = true;
                TxtBalance.ReadOnly = true;
            }
            else
            {

            }



        }

        private void printPreviewDialog1_Load(object sender, EventArgs e)
        {

        }



    }
}
